package main

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"provider/config"
)

func main() {
	http.HandleFunc("/db_supports", dbSupport)
	http.HandleFunc("/db", db)
	http.HandleFunc("/connect", connect)
	http.HandleFunc("/showDatabases", showDatabases)
	http.HandleFunc("/showTables", showTables)
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		return
	}
}

func db(w http.ResponseWriter, r *http.Request) {
	//获取request中body的json数据
	var b = r.Body
	var s, _ = io.ReadAll(b)
	fmt.Println(string(s))

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write([]byte(`{"connectId":1}`))
}

func dbSupport(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		fmt.Println("this method is from GET  ")
	}
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write([]byte(`{"db_types":["mysql","postgres","sqlite"]}`))
}

func showTables(w http.ResponseWriter, r *http.Request) {
	var bytes, _ = io.ReadAll(r.Body)
	var s = string(bytes)
	var ccc = config.DbConfig{}
	err := json.Unmarshal([]byte(s), &ccc)
	if err != nil {
		return
	}
	var db = config.DbInstanceMap[ccc.DbId]

	//查询所有表名
	var tables []string
	result := db.Conn.Raw("SHOW TABLES").Scan(&tables)
	if result.Error != nil {
		fmt.Println("Failed to connect to database:", result.Error)
		return
	}
	fmt.Println("Connected to database:", tables)
}

func showDatabases(w http.ResponseWriter, r *http.Request) {
	var bytes, _ = io.ReadAll(r.Body)
	var s = string(bytes)
	var ccc = config.DbConfig{}
	err := json.Unmarshal([]byte(s), &ccc)
	if err != nil {
		return
	}
	var db = config.DbInstanceMap[ccc.DbId]
	// 定义一个切片来存储数据库名
	var databases []string
	// 执行 SHOW DATABASES 语句
	result1 := db.Conn.Raw("SHOW DATABASES").Scan(&databases)
	if result1.Error != nil {
		fmt.Println("获取数据库列表失败:", result1.Error)
		return
	}

	// 打印所有数据库名
	fmt.Println("所有逻辑数据库:")
	for _, dbName := range databases {
		fmt.Println(dbName)
	}
}

func connect(w http.ResponseWriter, r *http.Request) {
	var c = config.DbConfigFactory{
		R: r,
	}
	var mc = c.MakeConfig()
	var db = mc.MakeConnInstance()
	db.Connect()
}
